<template>
	<div class="ui-upfile-group">
		<div class="ui-upfile" :class="[disabledClass,classname,v.isnew]" :style="[style,!isImg?{display:'block',marginBottom:'5px'}:'']" v-if="isshow" v-for="(v,k) in data">



			<template v-if="!isImg">
				<input type="file" :name="name" class="ui-upfile-file" @change="change(v)" :disabled="disabled" style="width:60px;" v-if="version>9">
				<ui-btn>上传</ui-btn>
				<span class="ui-upfile-name">
					{{v.filepath?v.filepath:(!v.isupload?'':v.uploadSuccess?"正在上传":"上传失败")}}
				</span>
				<i class="ui-upfile-del2 font" @click="del(k)" v-show="v.filepath">&#xe641;</i>
			</template>


			<template v-else>
				<div class="ui-upfile-img">
					<div class="ui-upfile-tip" :class="v.isupload">
						{{v.uploadSuccess?"正在上传":"上传失败"}}
					</div>
					<span class="ui-upfile-del font" @click="del(k)">&#xe641;</span>
					<div class="ui-upfile-img-block" v-show="divsrc" ref="divsrc"></div>
					<img :src="v.filepath" v-show="v.filepath" class="ui-upfile-img-block"/>
					<div class="ui-upfile-bg font" v-show="!v.filepath && !divsrc">&#xe6b9;</div>
					<input type="file" :name="name" class="ui-upfile-file ui-upfile-file2"  @change="change(v)" :disabled="disabled" v-if="version>9"/>
				</div>
			</template>
		</div>
	</div>
</template>

<script>
	import btn from "./ui_btn.vue";
	/*
	组件属性[
		style:自定义样式
		class:自定义class
		disabled：是否交互 true/false
		name:文件域name
		type:"文件类型，数组[jpg,gif,png,......]",
		filepath:初始化文件路径
		max:最大文件数,
		data:初始化上传列表数据
			 [
			 	{filepath:""},...
			 ]
		isAjax:是否异步上传 true/false
		ajax:异步上传选项
			 {
			 	url:'',//上传地址
			 	callback(res):回调函数,返回{state:true/false,data:回传数据}
			 }

	]
	组件事件[
		change:选项发生改变时回调的父组件方法，callback(obj[当前实例])
	]
	*/
	export default{
		props:{
			'style':{type:null,default:""},
			'classname':{type:null,default:""},
			'disabled':{type:Boolean,default:false},
			'name':{type:String,default:""},
			'type':{type:Array,default:['jpg','jpeg','png']},
			"filepath":{type:String,default:""},
            'max':{type:Number,default:1},
            'data':{type:Object,default:[]},
            'isAjax':{type:Boolean,default:true},
			'ajax':{type:Object,default:{url:'up.php',callback:false}},
		},
		data(){
			return {
				uiType:"ui-upfile",
				disabledClass:this.disabled?"disabled":"",
				isImg:false,
				divsrc:'',
				isshow:true,
				version:window.IEVersion,
            }
		},
		methods:{			
			click(){
				if(!this.disabled){
					this.$refs.file.click();
				}
			},
			del(k){
				this.data.splice(k,1);
                if(this.data.length<this.max) {
                    let isnew=false;
                    for (let i = 0; i < this.data.length; i++) {
						if(this.data[i].isnew=='new'){
                            isnew=true;
                            break;
						}
                    }
                    if(!isnew)this.data.push({filepath:"",isshow:true,isnew:'new'});
                }

			},
			change(data){
				let fileArea=event.srcElement;
				let types=this.type.join('|');
				if(!fileArea.value.match(new RegExp("("+types+")$",'g'))){
					alert('文件格式错误');
					return false;
				}
                data.isnew="";
				if(types.indexOf('jpg')!=-1||types.indexOf('jpeg')!=-1||types.indexOf('gif')!=-1||types.indexOf('png')!=-1){
					this.isImg=true;
				}
				if(!this.isImg){
					let filePath=fileArea.value.split('\\');
                    data.filepath=filePath[filePath.length-1];
				}else{
                    data.filepath="";
					if (fileArea.files && fileArea.files[0]){//非IE
						//safari6以下版本不支持  window.URL
						data.filepath=window.URL.createObjectURL(fileArea.files[0]);
				        this.divsrc="";
				        this.$emit('change',fileArea)//选择成功执行回调
				    }else{
				    	//IE
						this.divsrc=true;
                        let localImagId=this.$refs.divsrc;
				    	fileArea.select();
				        window.parent.document.body.focus();
				        let imgSrc = document.selection.createRange().text;
				        try{
				        	//图片异常的捕捉，防止用户修改后缀来伪造图片
				        	//ie8以上版本不允许直接通过本地路径展示本地图片，这里采用ie滤镜显示
                            data.filepath="";
				        	this.divsrc=true;
				            localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="+imgSrc+")";
				            this.$emit('change',fileArea);//选择成功执行回调
				        } catch(e){}
				        document.selection.empty();
				    }
				}

                if(this.isAjax){
                    if(window.IEVersion>9) {
                        this.ajaxFun(fileArea, data);
                    }else{
                        this.ajaxFunIE(fileArea,data);
                    }
                }

				if(this.data.length<this.max){
                    this.data.push({filepath:"",isshow:true,isnew:'new',isupload:'',uploadSuccess:false});
                }
			},
			//异步上传
			ajaxFun(inputObj,data){
                data.isupload=true;
                let formData = new FormData();
                let XHR= new XMLHttpRequest();
                let self=this;
                formData.append(this.name,inputObj.files[0]);
                XHR.open("POST",this.ajax.url);
                XHR.onload = function() {
                    if (XHR.status == 200) {
                        data.isupload=false;
                        data.uploadSuccess=true;
                       	console.log(XHR.responseText);
                        if(self.ajax.callback)self.ajax.callback(XHR.responseText)
                    } else {
                        //console.log('Error:'+XHR.status);
                        data.uploadSuccess=false;
                    }
                }
                XHR.send(formData);
            },
			//不支持FormData的ie
			ajaxFunIE(imageFile,data){

            }
		},
		components:{
			"ui-btn":btn,
			//"ui-alert":alert
		},
		created(){
			let types=this.type.join('|');
			if(types.indexOf('jpg')!=-1||types.indexOf('jpeg')!=-1||types.indexOf('gif')!=-1||types.indexOf('png')!=-1){
				this.isImg=true;
			}

            for(let i in this.data){
                this.data[i].isnew="";
                this.data[i].isshow=true;
                this.data[i].isupload='';
                this.data[i].uploadSuccess=false;
            }

			if(this.data.length<this.max || this.data.length==0){
				this.data.push({filepath:"",isshow:true,isnew:'new',isupload:'',uploadSuccess:false});
			}
		}
	}


</script>

